﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BLToolkit.DataAccess;
using Platform.Model;
using iTextSharp.text;
using iTextSharp.text.pdf;


namespace PlatformManagement
{
    public partial class StockReportForm : DevComponents.DotNetBar.Metro.MetroForm
    {
        public StockReportForm()
        {
            InitializeComponent();
            dgvReport.AutoGenerateColumns = false;
            
        }

        private void StockReportForm_Load(object sender, EventArgs e)
        {
           // int id = WorkSession.Current.Market.ID;
            dgvReport.DataSource = new BindingSource {DataSource = ViewStock.Objects.Where(x=>x.MarketId==1).ToList()};
           // dgvReport.DataSource = ViewStock.Objects.Where(x => x.ArtName.IndexOf("long") != -1).ToList();
        }

        private void dtpDate_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                dgvReport.DataSource = ViewStock.Objects.Where(x => x.OrderDate.Day == dtpDate.Value.Day && x.OrderDate.Month == dtpDate.Value.Month && x.OrderDate.Year == dtpDate.Value.Year).ToList();
            }
            catch (Exception ex)
            {

                MessageBox.Show("Error: " + ex.Message);
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "(*.xls;*.xlsx)|*.xls;*.xlsx";
            saveFileDialog1.FileName = "*.xlsx";
            if (dgvReport.Rows.Count - 1 == 0)
                MessageBox.Show("Không có dữ liệu để xuất");
            else
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {

                    ExportToExcel(saveFileDialog1.FileName);
                }


        }
        private void ExportToExcel(string _path)
        {
            try
            {
                // tạo ứng dụng Excel
                Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
                // Tạo WorkBook mới 
                Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
                // tạo Sheet nới 
                Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
                app.Visible = true;
                //Khai báo Sheet đầu tiên để làm việc
                worksheet = workbook.Sheets["Sheet1"];
                worksheet = workbook.ActiveSheet;
                // Thay đổi tên Sheet
                worksheet.Name = "Exported from gridview";
                // Lưu trữ dữ liệu cho dòng header
                for (int i = 1; i < dgvReport.Columns.Count + 1; i++)
                    worksheet.Cells[1, i] = dgvReport.Columns[i - 1].HeaderText;

                // Lưu trữ dữ liệu cho các dòng, cột 
                for (int i = 0; i < dgvReport.Rows.Count - 1; i++)
                    for (int j = 0; j < dgvReport.Columns.Count; j++)
                    {
                        worksheet.Cells[i + 2, j + 1] = dgvReport.Rows[i].Cells[j].Value.ToString();
                       
                      
                    }
           
                // Lưu file 
                workbook.SaveAs(_path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                // Thoát khỏi ứng dụng Excel                   
                app.Quit();
                

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //DataTable tb = (DataTable)dgvReport.DataSource;
            //ReportForm frm = new ReportForm(tb);
            //frm.ShowDialog();
            saveFileDialog1.Filter = "(*.Pdf|*.Pdf)";
            saveFileDialog1.FileName = "*.Pdf";
            if (dgvReport.Rows.Count - 1 == 0)
                MessageBox.Show("Không có dữ liệu để xuất");
            else
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {

                    ExportToPDF(saveFileDialog1.FileName);
                }
        }
        

        private void ExportToPDF(string _path)
        {
            try
            {
                Document doc = new Document(PageSize.A3);
                PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(_path, FileMode.Create));
                doc.Open();
                PdfPTable table = new PdfPTable(dgvReport.Columns.Count);
                int[] mang = { 100, 300, 80, 85, 300, 80, 80, 80, 100 };
                table.SetWidths(mang);
                for (int i = 0; i < dgvReport.Columns.Count; i++)
                {
                    table.AddCell(new Phrase(dgvReport.Columns[i].HeaderText, FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD)));
                }
                table.HeaderRows = 1;
                for (int i = 0; i < dgvReport.Rows.Count; i++)
                {
                    for (int j = 0; j < dgvReport.Columns.Count; j++)
                    {
                        if (dgvReport[j, i].Value != null)
                            table.AddCell(new Phrase(dgvReport[j, i].Value.ToString(), FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL)));
                    }
                }
                doc.Add(table);
                doc.Close();
                if(MessageBox.Show("Export successful, you want to open it?", "Notice", MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question)==DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start("\"" + _path + "\"");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: \n" + ex.Message);
            }
         
        }
        
        //Tìm kiếm tên một nhà cung cấp hoặc một mặt hàng
        private void txt1_TextChanged(object sender, EventArgs e)
        {
            if (cbbType.Text == "Supplier Name")
                dgvReport.DataSource =ViewStock.Objects.Where(x => x.SupName.IndexOf(txt1.Text) != -1).ToList();
            else if(cbbType.Text=="Article Name")
                dgvReport.DataSource = ViewStock.Objects.Where(x => x.ArtName.IndexOf(txt1.Text) != -1).ToList();
        }

        private void cbbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbbType.Text)
            {
                case "All":
                    dtpDate.Enabled = false;
                    txt1.Enabled = false;
                    dgvReport.DataSource = ViewStock.Objects.All;
                    break;
                case "Date":
                    txt1.Enabled = false;
                    dtpDate.Enabled = true;
                    break;
                case "Supplier Name":
                     txt1.Enabled = true;
                    dtpDate.Enabled = false;
                    txt1.Text = "";
                    break;
                case "Article Name":
                    txt1.Enabled = true;
                    dtpDate.Enabled = false;
                    txt1.Text = "";
                    break;
            }
        }

      
    }
}
